import json
import threading

from django.shortcuts import render

# Create your views here.
import sys
from . import models
from ClientScan.settings import DR_SCAN_PATH
from django.http import JsonResponse
from django.core.serializers import serialize
from DRFileModel.ScanTools.IntervalScan import threading_wrapper

"""DrFileModel/views
    文件扫描接口的对外api, 受制于增强算法的泛化性能，暂时确定接口如下:
        1. 获取配置路径，返回模块配置的扫描路径
        2. 获取文件缓存， 返回尚未消费的`原图`文件文件列表(3个)
        3. 消费文件缓存， 通过文件的id，进行消费，消费过后的文件不在出现在接口2中
    
    对内的函数:
        1. 周期扫描函数, interval_scan, 周期使用DrScanTools和ScanCache比对
           新旧数据并刷新到数据库
"""

print(sys.argv)
if sys.argv[1] == "runserver":
    print("Loop threading starting...")
    interval_thread = threading.Thread(target=threading_wrapper, args=(DR_SCAN_PATH, ))
    interval_thread.start()


def get_scan_path(request):
    if request.method == "GET":
        return JsonResponse({'data': DR_SCAN_PATH}, status=200)
    return JsonResponse({'data': 'Invalid request'}, status=405)


def query_file_cache(request):
    if request.method == "GET":
        items = models.DRModel.objects.filter(is_ori=True, has_deal=False)[:3]
        item_list = []
        for e_i in items:
            item_list.append({"id": e_i.id, "file": e_i.file_name})
        json_data = json.dumps(item_list)
        return JsonResponse({'data': json_data})
    return JsonResponse({'data': 'Invalid request'}, status=405)


def consume_file_cache(request):
    if request.method == 'PUT':
        data = request.body.decode('utf-8')
        json_data = json.loads(data)
        consume_id = json_data['file_id']

        try:
            model_instance = models.DRModel.objects.get(id=consume_id)
            model_instance.has_deal = True
            model_instance.save()
            return JsonResponse({'data': 'success'}, status=200)
        except Exception as e:
            return JsonResponse({'data': 'Instance Not Found'}, status=500)
    return JsonResponse({'data': 'Invalid request'}, status=405)
